package com.yange.accountbook.ui

import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lxj.xpopup.XPopup
import com.yange.accountbook.R
import com.yange.accountbook.databinding.AccountModuleActivityLayoutBinding
import com.yange.accountbook.entity.BooksEntity
import com.yange.accountbook.entity.ModuleEntity
import com.yange.accountbook.entity.RuleEntity
import com.yange.accountbook.events.AccountDetailChangeEvent
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.popup.AddSplitPop
import com.yange.accountbook.utils.StringUtils
import com.yange.accountbook.utils.showToast
import com.yanzhenjie.recyclerview.*
import org.greenrobot.eventbus.EventBus

class AccountModuleActivity : BaseActivity<AccountModuleActivityLayoutBinding>() {

    lateinit var moduleOneAdapter: ModuleOneAdapter

    override fun getViewBinding() = AccountModuleActivityLayoutBinding.inflate(layoutInflater)

    override fun init() {

        moduleOneAdapter = ModuleOneAdapter()
        initListener()

        binding.dataList.layoutManager = LinearLayoutManager(this)
        binding.dataList.adapter = moduleOneAdapter

        getList()
    }


    private fun initListener() {

        moduleOneAdapter.addChildClickViewIds(R.id.tv_add,R.id.tv_remove_module)

        moduleOneAdapter.setOnItemChildClickListener(OnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tv_add) {
                var item = adapter.data[position] as ModuleEntity
                //添加新的规则
                XPopup.Builder(this)
                    .asCustom(AddSplitPop(this, item.id, object : AddSplitPop.DismissListener {
                        override fun dismiss() {
                            getList()
                        }
                    }))
                    .show()
            }
            if (view.id == R.id.tv_remove_module) {

                XPopup.Builder(this)
                    .asConfirm(
                        "提示", "确认删除该模式吗"
                    ) {
                        var item = adapter.data[position] as ModuleEntity
                        var arrayList = ArrayList<Int>()
                        arrayList.add(item.id)
                        RetrofitClient.getInstance()
                            .deleteRecord(this, Api.MODULE_DELETE, arrayList)
                            .subscribe(object :
                                RecObserver<BaseResponse<BooksEntity>>(this, true, false) {
                                override fun onSuccess(t: BaseResponse<BooksEntity>?) {
                                    getList()
                                }

                                override fun onFail(msg: String, code: Int) {
                                    showToast(msg)
                                }
                            })
                    }
                    .show()

            }
        })
        binding.smartRefresh.setOnRefreshListener {
            getList()
        }

        binding.titleBar.tvForward?.setOnClickListener {
            //新增分账
            XPopup.Builder(this)
                .hasStatusBarShadow(false)
                .hasShadowBg(true)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asInputConfirm(
                    "提示", "请输入模式名称"
                ) { text ->
                    if (text != null) {
                        saveModule(text)
                    }
                }
                .show()
        }
    }

    /**
     * 保存分账模式
     */
    private fun saveModule(text: String) {
        RetrofitClient.getInstance().invokePostBody(
            this, Api.SAVE_MODULE, mapOf(
                "name" to text
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(this, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                showToast("添加成功")
                getList()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }

    class ModuleOneAdapter :
        BaseQuickAdapter<ModuleEntity, BaseViewHolder>(R.layout.item_module_one_layout) {
        override fun convert(holder: BaseViewHolder, item: ModuleEntity) {
            holder.setText(R.id.tv_title, item.name)
            var modules = holder.getView<SwipeRecyclerView>(R.id.data_list)
            var rules = ModuleTwoAdapter()
            var swipeMenuCreator =
                SwipeMenuCreator { leftMenu, rightMenu, position ->
                    var deleteItem = SwipeMenuItem(context)
                    deleteItem.height = ViewGroup.LayoutParams.MATCH_PARENT
                    deleteItem.width = 200
                    deleteItem.textSize = 12
                    deleteItem.setBackground(R.color.my_red)
                    context.getColor(R.color.text_white).let { deleteItem.setTextColor(it) }
                    deleteItem.text = "删除"
                    rightMenu?.addMenuItem(deleteItem)
                }
            if (modules.adapter == null) {
                modules.setSwipeMenuCreator(swipeMenuCreator)
                modules.setOnItemMenuClickListener(object : OnItemMenuClickListener {
                    override fun onItemClick(menuBridge: SwipeMenuBridge?, adapterPosition: Int) {
                        menuBridge?.closeMenu()
                        // 左侧还是右侧菜单：
                        val direction = menuBridge!!.direction
                        // 菜单在Item中的Position：
                        val menuPosition = menuBridge.position
                        if (direction == -1 && menuPosition == 0) {
                            XPopup.Builder(context)
                                .asConfirm(
                                    "提示", "确认删除该规则吗"
                                ) {
                                    deleteRule(
                                        rules.data[adapterPosition],
                                        adapterPosition,
                                        rules
                                    )
                                }
                                .show()
                        }
                    }
                })
            }
            modules.layoutManager = LinearLayoutManager(context)
            modules.adapter = rules
            rules.setNewInstance(item.rules)
        }

        private fun deleteRule(
            record: RuleEntity,
            index: Int,
            twoAdapter: ModuleTwoAdapter
        ) {
            RetrofitClient.getInstance()
                .deleteRecord(context, Api.MODULE_RULES_DELETE, listOf(record.id))
                .subscribe(object : RecObserver<BaseResponse<Any>>(context, true, false) {
                    override fun onSuccess(t: BaseResponse<Any>?) {
                        showToast("删除成功")
                        twoAdapter.data.removeAt(index)
                        twoAdapter.notifyDataSetChanged()
                        EventBus.getDefault()
                            .post(AccountDetailChangeEvent(record.bookId, record.accountId))
                    }

                    override fun onFail(msg: String, code: Int) {
                        showToast(msg)
                    }

                })
        }

    }

    class ModuleTwoAdapter :
        BaseQuickAdapter<RuleEntity, BaseViewHolder>(R.layout.item_module_two_layout) {
        override fun convert(holder: BaseViewHolder, item: RuleEntity) {
            holder.setText(R.id.tv_title, item.bookName + "-" + item.accountName)
            holder.setText(R.id.tv_money, StringUtils.getNoMoreThanTwoDigits(item.money))
        }
    }


    private fun getList() {
        RetrofitClient.getInstance().invokePostBody(this, Api.SPLIT_ACCOUNT_LIST, mapOf())
            .subscribe(object : RecObserver<BaseResponse<List<ModuleEntity>>>(this, false, false) {
                override fun onSuccess(t: BaseResponse<List<ModuleEntity>>?) {
                    binding.smartRefresh.finishRefresh()
                    moduleOneAdapter.setNewInstance(t?.data as MutableList<ModuleEntity>?)
                }

                override fun onFail(msg: String, code: Int) {
                    binding.smartRefresh.finishRefresh()
                    showToast(msg)
                }
            })
    }
}